package com.hethongviet.job.helpers;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.hethongviet.job.AppMain;

public class ServiceHelper
{
	public static final String URL = "http://www.quanlytiendo.com";

	public static final String URL_DOWNLOAD_IMAGE = "/ImageResource/";
	public static final String URL_DOWNLOAD_FILE = "/DocumentResource/";
	public static final String URL_DOWNLOAD_AUDIO = "/AudioResource/";

	public static final int LOCATION_ATTR_NONE = 10000;
	public static final String LOCATION_SEPERATE = ",";

	public static final String RESULT_OK = "OK";
	public static final String ERROR_OUT_OF_MEMORY = "<<<";

	public static final String USERNAME = "UserName";
	public static final String PASSWORD = "Password";
	public static final String ACTIVE_CODE = "ActiveCode";
	public static final String APP_NAME = "AppName";
	public static final String MEMBER_ID = "FK_MemberID";
	public static final String IS_MANAGE_PROJECT = "IsManagerJob";
	public static final String PROJECT_ID = "FK_JobID";
	// public static final String JSON_STRING = "JSON";
	public static final String TASK_ID = "PK_ID";
	public static final String IMAGE = "ImageWork";
	public static final String IMAGE_DATA = "ImageWorkByte";
	public static final String MEMBER_ASSIGN_ID = "FK_MemberAssignID";
	public static final String LOCATION = "Latitude";
	public static final String LOCATION_FINISH = "LatitudeAfter";
	public static final String IMAGE_FINISH = "ImageWorkAfter";
	public static final String IMAGE_FINISH_DATA = "ImageWorkAfterByte";
	public static final String TASK_ID_FULL = "FK_JobItemID";
	public static final String COMMENT = "Comment";
	public static final String COMMENT_ID = "PK_ID";	
	public static final String ATTACHMENT_NAME = "AttachmentName";
	public static final String ATTACHMENT_DATA = "AttachmentNameByte";
	public static final String AUDIO_NAME = "AudioName";
	public static final String AUDIO_DATA = "AudioByte";
	public static final String PASSWORD_OLD = "OldPassword";
	public static final String PASSWORD_NEW = "NewPassword";

	public ServiceHelper()
	{
	}

	public static String doLogin(String username, String password,
			String activationCode, String appName)
	{
		String methodName = "CheckUserName";

		// Building post parameters: key and value pair
		List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
		nameValuePair.add(new BasicNameValuePair(USERNAME, username));
		nameValuePair.add(new BasicNameValuePair(PASSWORD, password));
		nameValuePair.add(new BasicNameValuePair(ACTIVE_CODE, activationCode));
		nameValuePair.add(new BasicNameValuePair(APP_NAME, appName));

		return doPost(methodName, nameValuePair);
	}

	@SuppressWarnings("unused")
	private static String getResultStringUseInstreamReader(
			InputStream inputStream)
	{
		InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
		/* Get the string return */
		int charRead = 0;
		String resultStr = "";
		char[] charBuffer = new char[2000];
		try
		{
			while ((charRead = inputStreamReader.read(charBuffer)) > 0)
			{
				resultStr += String.valueOf(charBuffer, 0, charRead);
				charBuffer = new char[2000];
			}
		} catch (IOException e)
		{
			e.printStackTrace();
		}
		AppMain.debug(resultStr);
		return resultStr;
	}

	@SuppressWarnings("unused")
	private static String getResultString(InputStream inputStream)
	{
		String resultStr = "";
		try
		{
			BufferedReader bufferReader = new BufferedReader(new InputStreamReader(inputStream));
			String line;
			StringBuffer response = new StringBuffer();
			while ((line = bufferReader.readLine()) != null)
			{
				response.append(line);
			}
			bufferReader.close();
			resultStr = response.toString();
		} catch (IOException e)
		{
			e.printStackTrace();
		}

		AppMain.debug(resultStr);
		return resultStr;
	}

	public static String doGetListOfProjects(String username, String memberId,
			boolean isManagerJobs)
	{
		String methodName = "GetJobList";

		// Building post parameters: key and value pair
		List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
		nameValuePair.add(new BasicNameValuePair(MEMBER_ID, memberId));
		nameValuePair.add(new BasicNameValuePair(USERNAME, username));
		nameValuePair.add(new BasicNameValuePair(IS_MANAGE_PROJECT, (isManagerJobs ? "True" : "False")));

		return doPost(methodName, nameValuePair);
	}

	public static String doGetListOfAllTasks(String username, String memberId,
			boolean isManagerJobs)
	{
		String methodName = "GetJobItemAll";

		// Building post parameters: key and value pair
		List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
		nameValuePair.add(new BasicNameValuePair(MEMBER_ID, memberId));
		nameValuePair.add(new BasicNameValuePair(USERNAME, username));
		nameValuePair.add(new BasicNameValuePair(IS_MANAGE_PROJECT, (isManagerJobs ? "True" : "False")));

		return doPost(methodName, nameValuePair);
	}

	public static String doGetListOfTasks(String projectId, String username,
			String memberId, boolean isManagerJobs)
	{
		String methodName = "GetJobItemByJobID";

		// Building post parameters: key and value pair
		List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
		nameValuePair.add(new BasicNameValuePair(PROJECT_ID, projectId));
		nameValuePair.add(new BasicNameValuePair(MEMBER_ID, memberId));
		nameValuePair.add(new BasicNameValuePair(USERNAME, username));
		nameValuePair.add(new BasicNameValuePair(IS_MANAGE_PROJECT, (isManagerJobs ? "True" : "False")));

		return doPost(methodName, nameValuePair);
	}

	public static String doStartTask(String memberId, String imageWorkPath,
			String imageData, String taskId, double latitude, double longitude)
	{
		String methodName = "StartJobItem";

		String latitudeString = "";
		if (latitude != LOCATION_ATTR_NONE)
		{
			latitudeString = latitude + LOCATION_SEPERATE + longitude;
		}

		// Building post parameters: key and value pair
		List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
		nameValuePair.add(new BasicNameValuePair(TASK_ID, taskId));
		nameValuePair.add(new BasicNameValuePair(IMAGE, getString(imageWorkPath)));
		nameValuePair.add(new BasicNameValuePair(MEMBER_ASSIGN_ID, memberId));
		nameValuePair.add(new BasicNameValuePair(LOCATION, latitudeString));
		nameValuePair.add(new BasicNameValuePair(IMAGE_DATA, getString(imageData)));

		return doPost(methodName, nameValuePair);
	}

	public static String doStartTaskLowNetwork(String memberId, String taskId, double latitude, double longitude)
	{
		String methodName = "StartJobItemGPRS";

		String latitudeString = "";
		if (latitude != LOCATION_ATTR_NONE)
		{
			latitudeString = latitude + LOCATION_SEPERATE + longitude;
		}

		// Building post parameters: key and value pair
		List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
		nameValuePair.add(new BasicNameValuePair(TASK_ID, taskId));
		nameValuePair.add(new BasicNameValuePair(MEMBER_ASSIGN_ID, memberId));
		nameValuePair.add(new BasicNameValuePair(LOCATION, latitudeString));
		
		return doPost(methodName, nameValuePair);
	}

	public static String doSyncStartTask(String imageWorkPath,
			String imageData, String taskId)
	{
		String methodName = "SyncStartJobItemGPRS";

		// Building post parameters: key and value pair
		List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
		nameValuePair.add(new BasicNameValuePair(TASK_ID, taskId));
		nameValuePair.add(new BasicNameValuePair(IMAGE, getString(imageWorkPath)));
		nameValuePair.add(new BasicNameValuePair(IMAGE_DATA, getString(imageData)));

		return doPost(methodName, nameValuePair);
	}

	/**
	 * example: getJsonObject(a, value_a, b, value_b,...);
	 * 
	 * @param strings
	 * @return
	 */
	@SuppressWarnings("unused")
	private static JSONObject getJsonObject(String... strings)
	{
		if (strings.length == 0) return null;
		JSONObject jsonObject = new JSONObject();
		int length2 = strings.length >> 1;
		for (int index = 0; index < length2; index += 2)
		{
			try
			{
				jsonObject.put(strings[index], getString(strings[index + 1]));
			} catch (JSONException e)
			{
				e.printStackTrace();
				return null;
			}
		}
		return jsonObject;
	}

	@SuppressWarnings("unused")
	private static String getJsonString(String... strings)
	{
		int length = strings.length;
		if (length == 0) return null;
		String result = "{";
		result += "\"" + strings[0] + "\":\"" + getString(strings[1]) + "\"";
		for (int index = 2; index < length; index += 2)
		{
			result += ",\"" + strings[index] + "\":\""
					+ getString(strings[index + 1]) + "\"";
		}
		result += "}";
		return result;
	}

	public static String doFinishTask(String memberId, String imageWorkPath,
			String imageData, String taskId, double latitude, double longitude)
	{
		String methodName = "FinishJobItem";

		String latitudeAfter = "";
		if (latitude != LOCATION_ATTR_NONE)
		{
			latitudeAfter = latitude + LOCATION_SEPERATE + longitude;
		}

		// Building post parameters: key and value pair
		List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
		nameValuePair.add(new BasicNameValuePair(TASK_ID, taskId));
		nameValuePair.add(new BasicNameValuePair(IMAGE_FINISH, getString(imageWorkPath)));
		nameValuePair.add(new BasicNameValuePair(MEMBER_ASSIGN_ID, memberId));
		nameValuePair.add(new BasicNameValuePair(LOCATION_FINISH, latitudeAfter));
		nameValuePair.add(new BasicNameValuePair(IMAGE_FINISH_DATA, getString(imageData)));

		return doPost(methodName, nameValuePair);

	}

	public static String doFinishTaskLowNetwork(String memberId, String taskId, double latitude, double longitude)
	{
		String methodName = "FinishJobItemGPRS";

		String latitudeAfter = "";
		if (latitude != LOCATION_ATTR_NONE)
		{
			latitudeAfter = latitude + LOCATION_SEPERATE + longitude;
		}

		// Building post parameters: key and value pair
		List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
		nameValuePair.add(new BasicNameValuePair(TASK_ID, taskId));
		nameValuePair.add(new BasicNameValuePair(MEMBER_ASSIGN_ID, memberId));
		nameValuePair.add(new BasicNameValuePair(LOCATION_FINISH, latitudeAfter));
		
		return doPost(methodName, nameValuePair);

	}

	public static String doSyncFinishTask(String imageWorkPath,
			String imageData, String taskId)
	{
		String methodName = "SyncFinishJobItemGPRS";

		// Building post parameters: key and value pair
		List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
		nameValuePair.add(new BasicNameValuePair(TASK_ID, taskId));
		nameValuePair.add(new BasicNameValuePair(IMAGE_FINISH, getString(imageWorkPath)));
		nameValuePair.add(new BasicNameValuePair(IMAGE_FINISH_DATA, getString(imageData)));

		return doPost(methodName, nameValuePair);

	}

	public static String doAddComment(String taskId, String commentString,
			String memberId, String imageWorkPath, String imageWorkData,
			String attachmentPath, String attachmentData, String audioPath,
			String audioData, double latitude, double longitude)
	{
		String methodName = "SaveCommentJobItem";

		String latitudeString = "";
		if (latitude != LOCATION_ATTR_NONE)
		{
			latitudeString = latitude + LOCATION_SEPERATE + longitude;
		}

		// String sendData = "JSON=" + jsonObject.toString() + "&" + IMAGE_DATA
		// + "=" + getObject(imageWorkData) + "&" + ATTACHMENT_DATA + "=" +
		// getObject(attachmentData) + "&" + AUDIO_DATA + "=" +
		// getObject(audioData);
		// return doPost(methodName, sendData);

		// Building post parameters: key and value pair
		List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
		nameValuePair.add(new BasicNameValuePair(TASK_ID_FULL, taskId));
		nameValuePair.add(new BasicNameValuePair(COMMENT, commentString));
		nameValuePair.add(new BasicNameValuePair(MEMBER_ID, memberId));
		nameValuePair.add(new BasicNameValuePair(IMAGE, getString(imageWorkPath)));
		nameValuePair.add(new BasicNameValuePair(ATTACHMENT_NAME, getString(attachmentPath)));
		nameValuePair.add(new BasicNameValuePair(AUDIO_NAME, getString(audioPath)));
		nameValuePair.add(new BasicNameValuePair(IMAGE_DATA, getString(imageWorkData)));
		nameValuePair.add(new BasicNameValuePair(ATTACHMENT_DATA, getString(attachmentData)));
		nameValuePair.add(new BasicNameValuePair(AUDIO_DATA, getString(audioData)));
		nameValuePair.add(new BasicNameValuePair(LOCATION, latitudeString));

		return doPost(methodName, nameValuePair);
	}

	public static String doAddCommentLowNetwork(String taskId, String commentString,
			String memberId, double latitude, double longitude)
	{
		String methodName = "SaveCommentJobItemGPRS";

		String latitudeString = "";
		if (latitude != LOCATION_ATTR_NONE)
		{
			latitudeString = latitude + LOCATION_SEPERATE + longitude;
		}
		
		// Building post parameters: key and value pair
		List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
		nameValuePair.add(new BasicNameValuePair(TASK_ID_FULL, taskId));
		nameValuePair.add(new BasicNameValuePair(COMMENT, commentString));
		nameValuePair.add(new BasicNameValuePair(MEMBER_ID, memberId));
		nameValuePair.add(new BasicNameValuePair(LOCATION, latitudeString));

		return doPost(methodName, nameValuePair);
	}

	public static String doSyncAddComment(String commentId, String imageWorkPath, String imageWorkData,
			String attachmentPath, String attachmentData, String audioPath,
			String audioData)
	{
		String methodName = "SyncCommentJobItemGPRS";

		// Building post parameters: key and value pair
		List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
		nameValuePair.add(new BasicNameValuePair(COMMENT_ID, commentId));
		nameValuePair.add(new BasicNameValuePair(IMAGE, getString(imageWorkPath)));
		nameValuePair.add(new BasicNameValuePair(ATTACHMENT_NAME, getString(attachmentPath)));
		nameValuePair.add(new BasicNameValuePair(AUDIO_NAME, getString(audioPath)));
		nameValuePair.add(new BasicNameValuePair(IMAGE_DATA, getString(imageWorkData)));
		nameValuePair.add(new BasicNameValuePair(ATTACHMENT_DATA, getString(attachmentData)));
		nameValuePair.add(new BasicNameValuePair(AUDIO_DATA, getString(audioData)));
		
		return doPost(methodName, nameValuePair);
	}

	public static String doAddReport(String taskId, String commentString,
			String memberId, String imageWorkPath, String imageWorkData,
			String audioPath,
			String audioData, double latitude, double longitude)
	{
		String methodName = "SaveReportJobItem";

		String latitudeString = "";
		if (latitude != LOCATION_ATTR_NONE)
		{
			latitudeString = latitude + LOCATION_SEPERATE + longitude;
		}

		// String sendData = "JSON=" + jsonObject.toString() + "&" + IMAGE_DATA
		// + "=" + getObject(imageWorkData) + "&" + ATTACHMENT_DATA + "=" +
		// getObject(attachmentData) + "&" + AUDIO_DATA + "=" +
		// getObject(audioData);
		// return doPost(methodName, sendData);

		// Building post parameters: key and value pair
		List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
		nameValuePair.add(new BasicNameValuePair(TASK_ID_FULL, taskId));
		nameValuePair.add(new BasicNameValuePair(COMMENT, commentString));
		nameValuePair.add(new BasicNameValuePair(MEMBER_ID, memberId));
		nameValuePair.add(new BasicNameValuePair(IMAGE, getString(imageWorkPath)));
		nameValuePair.add(new BasicNameValuePair(AUDIO_NAME, getString(audioPath)));
		nameValuePair.add(new BasicNameValuePair(IMAGE_DATA, getString(imageWorkData)));
		nameValuePair.add(new BasicNameValuePair(AUDIO_DATA, getString(audioData)));
		nameValuePair.add(new BasicNameValuePair(LOCATION, latitudeString));

		return doPost(methodName, nameValuePair);
	}

	public static String doAddReportLowNetwork(String taskId, String commentString,
			String memberId, double latitude, double longitude)
	{
		String methodName = "SaveReportJobItemGPRS";

		String latitudeString = "";
		if (latitude != LOCATION_ATTR_NONE)
		{
			latitudeString = latitude + LOCATION_SEPERATE + longitude;
		}
		
		// Building post parameters: key and value pair
		List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
		nameValuePair.add(new BasicNameValuePair(TASK_ID_FULL, taskId));
		nameValuePair.add(new BasicNameValuePair(COMMENT, commentString));
		nameValuePair.add(new BasicNameValuePair(MEMBER_ID, memberId));
		nameValuePair.add(new BasicNameValuePair(LOCATION, latitudeString));

		return doPost(methodName, nameValuePair);
	}

	public static String doSyncAddReport(String commentId, String imageWorkPath, String imageWorkData,
			String audioPath,
			String audioData)
	{
		String methodName = "SyncReportJobItemGPRS";

		// Building post parameters: key and value pair
		List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
		nameValuePair.add(new BasicNameValuePair(COMMENT_ID, commentId));
		nameValuePair.add(new BasicNameValuePair(IMAGE, getString(imageWorkPath)));
		nameValuePair.add(new BasicNameValuePair(AUDIO_NAME, getString(audioPath)));
		nameValuePair.add(new BasicNameValuePair(IMAGE_DATA, getString(imageWorkData)));
		nameValuePair.add(new BasicNameValuePair(AUDIO_DATA, getString(audioData)));
		
		return doPost(methodName, nameValuePair);
	}

	public static String doGetListOfComments(String taskId)
	{
		String methodName = "GetCommentJobItem";

		// Building post parameters: key and value pair
		List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
		nameValuePair.add(new BasicNameValuePair(TASK_ID_FULL, taskId));

		return doPost(methodName, nameValuePair);

	}

	public static String doChangePass(String username, String passCurrent,
			String passNew)
	{
		String methodName = "ChangePasswordHTTP";

		// Building post parameters: key and value pair
		List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
		nameValuePair.add(new BasicNameValuePair(PASSWORD_OLD, passCurrent));
		nameValuePair.add(new BasicNameValuePair(PASSWORD_NEW, passNew));
		nameValuePair.add(new BasicNameValuePair(USERNAME, username));

		return doPost(methodName, nameValuePair);
	}

	@SuppressWarnings("unused")
	private static String doPost(String methodName, String sendData)
	{
		try
		{
			String url = URL + "/User/" + methodName + ".aspx";
			if (AppMain._user.getDomain() != null
					&& !AppMain._user.getDomain().trim().equals(""))
			{
				url = URL + "/" + AppMain._user.getDomain() + "/User/"
						+ methodName + ".aspx";
			}

			AppMain.debug(url);

			// InputStream inputStream =
			String result = new OpenHttpConnection().post(url, sendData);

			if (result == null)
			{
				AppMain.debug("Error network! Please check the network!");
			}
			else
			{
				// String result = getResultString(inputStream);
				AppMain.debug("connect ok!!!!!!!!");
				AppMain.debug("Result:\"" + result + "\"");
				return result;
			}

		} catch (IOException e)
		{
			e.printStackTrace();
		}
		return null;
	}

	public static String doPost(String methodName,
			List<NameValuePair> nameValuePairs)
	{
		String url = URL + "/User/" + methodName + ".aspx";
		if (AppMain._user.getDomain() != null
				&& !AppMain._user.getDomain().trim().equals(""))
		{
			url = URL + "/" + AppMain._user.getDomain() + "/User/" + methodName
					+ ".aspx";
		}

		// AppMain.debug(url + nameValuePairs.toString());

		String responseString = null;

		AppMain.debug("POST 11111111111111");
		// Creating HTTP client
		HttpClient httpClient = new DefaultHttpClient();
		

		AppMain.debug("POST 22222222222");
		// Creating HTTP Post
		HttpPost httpPost = new HttpPost(url);		
		
		AppMain.debug("POST 33333333333");
		// URL Encoding the POST parameters
		try
		{
			if (methodName.equalsIgnoreCase("SaveCommentJobItem")) httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "utf-8"));
			else httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		} catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		} catch (OutOfMemoryError e)
		{
			e.printStackTrace();
			httpPost = null;
			httpClient = null;
			nameValuePairs = null;
			responseString = null;
			System.gc();
			return ERROR_OUT_OF_MEMORY;
		}

		AppMain.debug("POST 4444444444444");
		// Making HTTP Request
		try
		{
			HttpResponse response = httpClient.execute(httpPost);

			// writing response to log
			Log.d("Http Response.getStatusLine:", response.getStatusLine().toString());

			responseString = OpenHttpConnection.getResponseBody(response);

			Log.d("Http Response:", "" + responseString);
		} catch (ClientProtocolException e)
		{
			e.printStackTrace();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
		AppMain.debug("POST OK!!!!!!!!!");
		return responseString;
	}

	private static String getString(String stringValue)
	{
		return (stringValue == null) ? "" : stringValue;
	}

	@SuppressWarnings("unused")
	private static Object getObject(Object objectValue)
	{
		// return (objectValue == null) ? JSONObject.NULL : objectValue;
		return (objectValue == null) ? "" : objectValue;
	}

}
